package com.cangshi.controller;

import com.alibaba.fastjson.JSON;
import com.cangshi.entity.Group;
import com.cangshi.entity.JsonObject;
import com.cangshi.entity.User;
import com.cangshi.entity.UserBaseInfo;
import com.cangshi.service.GroupService;
import com.cangshi.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Eoly on 2016/12/22.
 */

@Controller
public class GroupController {

    private static final Logger LOGGER = Logger.getLogger(GroupController.class);

    @Autowired
    GroupService groupService;

    @Autowired
    UserService userService;


    /**
     * 发起团
     *
     * @param group
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/group/add-group", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String findGroupType(@RequestBody Group group, HttpServletRequest request) {
        JsonObject jsonObject = new JsonObject();

        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        //获取用户id
        Integer userId = userLogin.getUserId();

        //LOGGER.debug("-----------》"+JSON.toJSONString(group));



        //检查完整性
        if (group != null &&
                group.getGroupTitle() != null &&
                group.getGroupSynopsis() != null &&
                group.getGroupDetail() != null &&
                group.getGroupFormat() != null &&
                group.getGroupGoodType() != null &&
                group.getGroupImgs() != null &&
                group.getGroupPrice() != null &&
                group.getGroupPriceOriginal() != null &&
                group.getGroupTargetNumber() != null
                ) {

            Integer aliveTime = 72;
            Integer groupStatus = -1;

            //检查权限
            switch (userLogin.getUserPower()){
                case 0:
                    jsonObject.setError(611);
                    jsonObject.setMes("该用户目前不能发团");
                    return JSON.toJSONString(jsonObject);
                case 1:
                    break;
                case 2:
                    aliveTime = 120;
                    groupStatus = 0;
                    break;
                case 3:
                    aliveTime = -1;
                    groupStatus = 0;
                    break;
            }


            group.setGroupInitiatorId(userId);
            group.setGroupStatus(groupStatus);
            group.setGroupAliveHours(aliveTime);
            if (group.getGroupPostage() == null) group.setGroupPostage(10.0);

            //添加动作
            Integer result = groupService.addGroup(group);
            jsonObject.setError(result == 1 ? 0 : 603);
            if (result != 1) {
                jsonObject.setMes("添加团失败");
            } else {
                jsonObject.setMes("添加团成功");
                jsonObject.setId(groupService.getIdFromLastAdd());
            }

        } else {
            jsonObject.setMes("团信息不完整，请重新填写");
            jsonObject.setError(604);
        }


        //返回结果
        return JSON.toJSONString(jsonObject);
    }


    /**
     * 查找指定类型的团，可以指定获取数量，以及类型和关键词
     *
     * @param goodsTypeId
     * @param line
     * @param next
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/group/find-groups", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String findGroups(@RequestParam(required = false) String keyWord, @RequestParam(required = false) Integer goodsTypeId, @RequestParam(required = false) Integer line, @RequestParam(required = false) Integer next) {
        JsonObject<Group> jsonObject = new JsonObject<Group>();

        //通过指定条件 获取团类型
        List<Group> Groups = groupService.findGroups(line, next, goodsTypeId, keyWord);

        if (Groups != null) {
            jsonObject.setError(0);
            jsonObject.setDataList(Groups);
            jsonObject.setMes("获取成功");
            if (Groups.isEmpty()) {
                jsonObject.setError(605);
                jsonObject.setMes("没有更多团啦");
            }
        } else {
            jsonObject.setError(602);
            jsonObject.setMes("获取失败");
        }

        return JSON.toJSONString(jsonObject);
    }

    /**
     * 获取所有团的总数
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/group/find-all-groups-count", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String findAllGroupsCount(@RequestParam(required = false) String keyWord, @RequestParam(required = false) Integer goodsTypeId) {
        JsonObject<Integer> jsonObject = new JsonObject<Integer>();

        Group checkGroup = new Group();
        //检查参数
        if (goodsTypeId != null ) {
            checkGroup.setGroupGoodType(goodsTypeId);
        }

        checkGroup.setGroupStatus(0);

        //通过指定id 获取团类型
        Integer count = groupService.findCountByGroup(checkGroup, keyWord);

        if (count != null) {
            jsonObject.setError(0);
            jsonObject.setData(count);
            jsonObject.setMes("共" + count + "条团信息");
        } else {
            jsonObject.setError(602);
            jsonObject.setMes("获取失败");
        }

        return JSON.toJSONString(jsonObject);
    }


    /**
     * 获取用户发起的团，可以指定获取个数以及团状态
     *
     * @param request
     * @param groupStatus
     * @param line
     * @param next
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/group/find-init-groups", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String findInitGroups(HttpServletRequest request,@RequestParam(required = false) Integer groupStatus, @RequestParam(required = false) Integer line, @RequestParam(required = false) Integer next) {
        JsonObject<Group> jsonObject = new JsonObject<Group>();

        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        //获取用户id
        Integer userId = userLogin.getUserId();

        //实例化一个团对象只包含发起者id
        Group checkGroup = new Group();
        checkGroup.setGroupInitiatorId(userId);
        checkGroup.setGroupStatus(groupStatus);

        //通过指定id 获取团类型
        List<Group> groups = groupService.findGroupsByGroup(checkGroup, line, next);

        if (groups != null) {
            jsonObject.setError(0);
            jsonObject.setDataList(groups);
            jsonObject.setMes("获取成功共" + groups.size() + "条团信息");
            if (groups.isEmpty()) {
                jsonObject.setError(605);
                jsonObject.setMes("该用户未发起团或者没有更多团");
            }
        } else {
            jsonObject.setError(602);
            jsonObject.setMes("获取失败");
        }

        return JSON.toJSONString(jsonObject);
    }

    /**
     * 获取用户发起所有团的总数,可以指定团状态
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/group/find-init-groups-count", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String findInitGroupsCount(HttpServletRequest request,@RequestParam(required = false) Integer groupStatus) {
        JsonObject<Integer> jsonObject = new JsonObject<Integer>();

        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        //获取用户id
        Integer userId = userLogin.getUserId();

        //实例化一个团对象只包含发起者id
        Group checkGroup = new Group();
        checkGroup.setGroupInitiatorId(userId);
        checkGroup.setGroupStatus(groupStatus);

        //通过指定id 获取团类型
        Integer count = groupService.findCountByGroup(checkGroup, null);

        if (count != null) {
            jsonObject.setError(0);
            jsonObject.setData(count);
            jsonObject.setMes("共" + count + "条团信息");
        } else {
            jsonObject.setError(602);
            jsonObject.setMes("获取失败");
        }

        return JSON.toJSONString(jsonObject);
    }


    /**
     * 获取团详细信息
     * @param groupId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/group/find-group", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String findGroup(@RequestParam Integer groupId) {
        JsonObject<Group> jsonObject = new JsonObject<Group>();

        //获取指定团
        Group resultGroup = groupService.findGroupByGroupId(groupId);

        if (resultGroup != null) {

            //获得发起用户所有信息
            User userInit = userService.getUserById(resultGroup.getGroupInitiatorId());

            if(userInit!=null) {

                //实例化一个用户对象，用以返回一些用户基础信息
                User resultUser = new User();
                resultUser.setUserId(userInit.getUserId());
                resultUser.setUserAvatar(userInit.getUserAvatar());
                resultUser.setUserPhoneNumber(userInit.getUserPhoneNumber());
                resultUser.setUserSex(userInit.getUserSex());
                resultUser.setUserPower(userInit.getUserPower());
                resultUser.setUserStatus(userInit.getUserStatus());

                //添加发起者信息到团信息中
                resultGroup.setGroupInitiator(resultUser);
                jsonObject.setMes("获取成功");
            }else {
                jsonObject.setMes("获取团成功，获取发起者信息失败");
            }

            jsonObject.setError(0);
            jsonObject.setData(resultGroup);
        } else {
            jsonObject.setError(710);
            jsonObject.setMes("获取失败");
        }

        return JSON.toJSONString(jsonObject);
    }

}
